package com.guarantee.server.config.acpectj;

import com.alibaba.fastjson2.JSON;
import com.guarantee.server.common.annotation.ResponseEncryption;
import com.guarantee.server.common.exception.ServiceException;
import com.guarantee.server.common.response.RestResponse;
import com.guarantee.server.common.utils.ServletUtils;
import com.guarantee.server.common.utils.StringUtils;
import com.guarantee.server.config.GuaranteeConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Base64Util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author huisonglin
 * @Description
 * @PackageName hainan-rest
 * @Package com.guarantee.server.config.acpectj
 * @Date 2022/11/29 17:27
 * @Version 1.0
 */
@Aspect
@Slf4j
@Component
//@ConditionalOnProperty(
//        prefix = "guarantee",
//        name = {"enableCheckSign"},
//        havingValue = "true"
//)
public class EncryptionResopnseAspect {

    @Resource
    GuaranteeConfig guaranteeConfig;


    @Pointcut("@annotation(com.guarantee.server.common.annotation.ResponseEncryption)")
    public void annotationPointCut() {
    }

    @Around("annotationPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        ResponseEncryption annotation = (ResponseEncryption) method.getAnnotation(ResponseEncryption.class);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        try {
            Object proceed = point.proceed();
            if (annotation != null) {
                RestResponse restResponse = (RestResponse) proceed;
                QingDaoResponse qingDaoResponse = new QingDaoResponse<>();
                qingDaoResponse.setResultcode(restResponse.isSuccess() ? "200" : "500");
                qingDaoResponse.setResultmessage(StringUtils.isBlank(restResponse.getMessage())?"SUCCESS":restResponse.getMessage());
                log.info("原始参数{}",JSON.toJSONString(restResponse.getData()));
                qingDaoResponse.setData(Base64Util.encode(JSON.toJSONString(restResponse.getData())));
                log.info("实际返回参数{}",JSON.toJSONString(qingDaoResponse));
                ServletUtils.responseString(response, JSON.toJSONString(qingDaoResponse));
            } else {
                return proceed;
            }
        } catch (Throwable e) {
            if (annotation != null) {
                QingDaoResponse qingDaoResponse = new QingDaoResponse();
                qingDaoResponse.setResultcode("500");
                qingDaoResponse.setResultmessage(e.getMessage());
                ServletUtils.responseString(response, JSON.toJSONString(qingDaoResponse));
            } else {
                throw new ServiceException(e.getMessage());
            }

        }
        return null;
    }
//    @AfterReturning(pointcut = "@annotation(responseEncryption)", returning = "restResponse")
//    public void doAfterReturning(JoinPoint joinPoint, ResponseEncryption responseEncryption, RestResponse restResponse)
//    {
//
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletResponse response = requestAttributes.getResponse();
//        HainanResponse hainanResponse = new HainanResponse();
//        hainanResponse.setResultCode(restResponse.getCode());
//        hainanResponse.setResult(restResponse.isSuccess()?"success":"failure");
//        hainanResponse.setResultMsg(restResponse.getMessage());
//        hainanResponse.setResultData(restResponse.getData());
//        String body = SMUtils.encryptBySM2(JSON.toJSONString(hainanResponse), guaranteeConfig.getPublicKey2());
//        responseString(response,JSON.toJSONString(body));
//    }

    @Data
    public static class QingDaoResponse<T> {
        private String resultcode;
        private String resultmessage;
        private String data;
    }


}
